#include "lnstack.h"

PLStack createEmptyStack()
{
    PLStack pstack = (PLStack) malloc (sizeof(struct stStack));
    if (pstack != NULL)
    {
        pstack->top = NULL;
        pstack->length = 0;
        return pstack;
    }
    
    return NULL;
}

int push(PLStack pstack, ELEMTYPE x)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    PNode p = (PNode) malloc (sizeof(struct Node));
    if (p != NULL)
    {
        p->info = x;
        p->link = pstack->top;
        pstack->top = p;
        pstack->length = pstack->length + 1;
        return 1;
    }

    return 0;
}

int pop(PLStack pstack)
{
    PNode p;
    if (pstack == NULL)
    {
        return -1;
    }
    
    if (isEmpty(pstack) == 1)
    { 
        return 0;
    }
    
    p = pstack->top;
    pstack->top = pstack->top->link;
    pstack->length = pstack->length - 1;
    free (p);
    
    return 1;
}

int top(PLStack pstack, ELEMTYPE *x)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    if (isEmpty(pstack) == 1)
    { 
        return 0;
    }
    
    *x = pstack->top->info;
    
    return 1;
}

int isEmpty(PLStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }

    return (pstack->length == 0);
  
}

int isFull(PLStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }
    
    return 0;
}

int length(PLStack pstack)
{
    if (pstack == NULL)
    {
        return -1;
    }

    return pstack->length;
}

int empty(PLStack pstack)
{

    if (pstack == NULL)
    {
        return -1;
    }
    
    while (!isEmpty(pstack))
    {
        pop(pstack);
    }
    
    return 1;
}

int destroy(PLStack *pstack)
{
    if (*pstack == NULL)
    {
        return -1;
    }
    
    empty(*pstack);
    free(*pstack);

    return 1;
}

int print(PLStack pstack)
{
    PNode p;
    SIZE_T i;

    if (pstack == NULL)
    {
        return -1;
    }
    
    p = pstack->top;
    i = length(pstack) - 1;
    #ifdef DEBUG
    printf("=========  STACK   ==========\n");
    printf("=======  %d ELEMENTS =========\n", i);
    #endif
    
    while (p != NULL)
    {
        printf("BUFFER[%d] = %c\n", i, p->info);
        i--;
        p = p->link;
    }
    
    return 1;
}
